<?php
namespace app\system\controller;

use app\common\model\DictModel;
use app\common\model\DictTypeModel;

class DictTypeController extends BaseController
{

    private $dictModel;
    private $dictTypeModel;

    /**
     * 初始化
     */
    protected function _initialize()
    {
        parent::_initialize();
        $this->dictModel     = new DictModel();
        $this->dictTypeModel = new DictTypeModel();
    }

    /**
     * 字典分类首页
     * @return mixed
     */
    public function index()
    {
        $list = $this->dictTypeModel->select();
        $this->assign('list', $list);//输出字典分类列
        return $this->fetch();
    }

    /**
     * 添加字典
     */
    public function add()
    {
        if ($this->request->isAjax()) {
            $data   = $this->request->param();
            $result = $this->validate($data, 'DictTypeValidate.add');
            if ($result !== true) {
                $this->error($result);
            }
            if ($this->dictTypeModel->addData($data)) {
                $this->success('添加成功!', url('index'));
            } else {
                $this->error($this->dictTypeModel->getError());
            }
        }
        return $this->fetch();
    }

    /**
     * 修改字典
     */
    public function edit()
    {
        if ($this->request->isAjax()) {
            $data = $this->request->param();
            if ($this->dictTypeModel->editData($data)) {
                $this->success('修改成功', url('index'));
            } else {
                $this->error($this->dictTypeModel->getError());
            }
        }
        $typeId = $this->request->param('type_id');
        $info   = $this->dictTypeModel->get(['type_id' => $typeId]);
        $this->assign('info', $info);
        return $this->fetch();
    }

    /**
     * 删除字典
     */
    public function del()
    {
        $typeId = $this->request->param('type_id');
        if ($this->dictModel->get(['type_id' => $typeId])) {
            $this->error('该分类下还存在字典项，不允许删除！');
        }
        $this->dictTypeModel->where('type_id', $typeId)->delete();
        $this->success('删除成功！');
    }
}
